package com.szholly.pro.watergas_server.ps.controller;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.util.ExportExcelUtils;
import com.szholly.pro.watergas_server.common.util.JsonUtil;
import com.szholly.pro.watergas_server.common.util.RedisHelper;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.pro.watergas_server.common.web.WebContext;
import com.szholly.pro.watergas_server.ps.service.DataAnalysisService;
import com.szholly.pro.watergas_server.ps.service.OnlineMonitorService;
import com.szholly.pro.watergas_server.ps.service.WaterQualityAnalysisService;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/waterQualityAnalysis/*")
public class waterQualityAnalysisController extends BaseController { 

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	WaterQualityAnalysisService waterQualityAnalysisService;
	
	@Autowired
	DataAnalysisService analysisService;
	
	@Autowired
	OnlineMonitorService onlineMonitorService;
	
	/**
	 * 污染物趋势分析
	 * gislin
	 * 2016年8月16日
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/queryTrend")
	public void queryTrend(HttpServletRequest resq, HttpServletResponse res) throws ParseException{
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String cycleType = RequestUnit.getString("cycleType");
		String stationid = RequestUnit.getString("stationid");
		String startDateStr = RequestUnit.getString("startDate");
		String endDateStr = RequestUnit.getString("endDate");
		String[] stationIds = stationid.split(",");
		HashMap<String,List<String>> mulitPolls = getMulitStationPoll();
		
		Date startDate = sf.parse(startDateStr+" 00:00:00");
		Date endDate = sf.parse(endDateStr + " 23:59:59");
		
		JSONObject result = waterQualityAnalysisService.queryTrend(startDate, endDate, cycleType, stationIds, mulitPolls);
		outString(result.toString());
	}
	
	/**
	 * 污染物趋势分析列表导出
	 * 熊伟
	 * 2017年6月1日
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws ParserException 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportTrendExcel")
	public void exportTrendExcel(HttpServletRequest resq, HttpServletResponse res) throws ParseException, IOException{
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			String cycleType = RequestUnit.getString("cycleType");
			String stationid = RequestUnit.getString("stationid");
			String startDateStr = RequestUnit.getString("startDate");
			String endDateStr = RequestUnit.getString("endDate");
			String[] stationIds = stationid.split(",");
			HashMap<String,List<String>> mulitPolls = getMulitStationPoll();
			List<RowBase> stationInfoList = waterQualityAnalysisService.queryStationInfo(stationIds);
			List<RowBase> BasinAndRiverCountList = waterQualityAnalysisService.queryBasinCountAndRiverCount(stationIds);
			Date startDate = sf.parse(startDateStr+" 00:00:00");
			Date endDate = sf.parse(endDateStr + " 23:59:59");
			String downLoadFileName="深圳市河流水质监测结果统计表.xls";
			String title="";
			if("year".equals(cycleType)) {
			    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			    String formatDate = sdf.format(startDate);
			    
			    //一年一个Excel Sheet页
				Calendar calBegin = Calendar.getInstance(); //获取日历实例  
				Calendar calEnd = Calendar.getInstance();  
				calBegin.setTime(startDate);
				calEnd.setTime(endDate);  
				int years = calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR);
				int startYear = calBegin.get(Calendar.YEAR);
				HashMap<String,Object> map = new HashMap<>();
				List<String> pollHeaders=new ArrayList<>();
				List<String> pollCodes=new ArrayList<>();
				List<HashMap<String, Object>> data = new ArrayList<>();
				List<RowBase>pollDeduplicated = new ArrayList<>();
				for(int i=startYear;i<startYear+years+1;i++) {
					HashMap<String, Object> excelData = new HashMap<>();
					startDate = waterQualityAnalysisService.getCurrYearFirst(i);
					Date end = waterQualityAnalysisService.getCurrYearLast(i);
					formatDate = sdf.format(end);
					title=formatDate+"深圳市河流水质监测结果统计表";
					map = waterQualityAnalysisService.queryTrendByYears(startDate, end, cycleType, stationIds, mulitPolls);
					pollDeduplicated = (List<RowBase>) map.get("pollDeduplicated");
					List<RowBase>datas = (List<RowBase>) map.get("data");
					List<RowBase>river = (List<RowBase>) map.get("river");
					List<RowBase>stations = (List<RowBase>) map.get("stations");
					excelData.put("river",river);
					excelData.put("stations",stations);
					excelData.put("pollName",pollDeduplicated);
					excelData.put("datas",datas);
					excelData.put("title",title);
					excelData.put("yearText",formatDate);
					data.add(excelData);
				}
				pollHeaders.add("流域");
				pollHeaders.add("河流名称");
				pollHeaders.add("断面名称");
				if(pollDeduplicated!=null && pollDeduplicated.size()>0) {
					for(int j=0;j<pollDeduplicated.size();j++){
						pollHeaders.add(pollDeduplicated.get(j).getSafeString("POLLNAME"));
						pollCodes.add(pollDeduplicated.get(j).getSafeString("POLLCODE"));
					}
				}
				responseData(BasinAndRiverCountList,stationInfoList,data,pollHeaders,pollCodes,downLoadFileName);
			} else {
				HashMap<String,Object> analysisData = waterQualityAnalysisService.queryTrendByYears(startDate, endDate, cycleType, stationIds, mulitPolls);
				List<Object> river = (List<Object>) analysisData.get("river");
				List<Object> riverSection = (List<Object>) analysisData.get("riverSection");
				List<Object> stations = (List<Object>) analysisData.get("stations");
				List<Object> polls = (List<Object>) analysisData.get("polls");
				List<Object> datas = (List<Object>) analysisData.get("data");
				List<Object> dateTexts = (List<Object>) analysisData.get("dateTexts");
				Calendar startCal = Calendar.getInstance();
				startCal.setTime(startDate);
				HashMap<String,Object> data=new HashMap<>();
				Calendar endCal = Calendar.getInstance();
				endCal.setTime(endDate);
				String titles="";
				if("day".equals(cycleType)) {
					titles = startCal.get(Calendar.YEAR) + "年" + (startCal.get(Calendar.MONTH)+1) + "月" + startCal.get(Calendar.DAY_OF_MONTH) + "日 ~"
							+ endCal.get(Calendar.YEAR) + "年" + (endCal.get(Calendar.MONTH)+1) + "月" + endCal.get(Calendar.DAY_OF_MONTH) + "日 "+"水质监测结果统计表";
				} else if("week".equals(cycleType)) {
					titles = startCal.get(Calendar.YEAR) + "年第" + (startCal.get(Calendar.WEEK_OF_YEAR)+1) + "周" + " ~"
							+ endCal.get(Calendar.YEAR) + "年 第" + (endCal.get(Calendar.WEEK_OF_YEAR)) + "周" +"水质监测结果统计表";
				} else if("month".equals(cycleType)) {
					titles = startCal.get(Calendar.YEAR) + "年" + (startCal.get(Calendar.MONTH)+1) + "月" + " ~"
							+ endCal.get(Calendar.YEAR) + "年" + (endCal.get(Calendar.MONTH)+1) + "月" +"水质监测结果统计表";
				} else if("quarter".equals(cycleType)) {
					titles = startCal.get(Calendar.YEAR) + "年第" + (waterQualityAnalysisService.getSeason(startDate)) + "季度" + " ~"
							+ endCal.get(Calendar.YEAR) + "年" + (waterQualityAnalysisService.getSeason(endDate)) + "季度" +"水质监测结果统计表";
				}
				data.put("titles",titles);
				data.put("river",river);
				data.put("riverSection",riverSection);
				data.put("stations",stations);
				data.put("polls",polls);
				data.put("datas",datas);
				data.put("dateTexts",dateTexts);
				HtmlToExcel(data, "sw/waterAnalysis.html", titles+".xls");
			}
			} catch (ParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	/**
	 * 污染源通量分析
	 * gislin
	 * 2016年8月16日
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/queryFlux")
	public void queryFlux(HttpServletRequest resq, HttpServletResponse res) throws ParseException{
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String cycleType = RequestUnit.getString("cycleType");
		String stationid = RequestUnit.getString("stationid");
		String stationSNid = RequestUnit.getString("contributeCode");
		String startDateStr = RequestUnit.getString("startDate");
		String endDateStr = RequestUnit.getString("endDate");
		String[] stationIds = stationid.split(",");
		
		String pollCode = RequestUnit.getString("pollCode");
		String[] pollList = null;
		String[] stationPolls = pollCode.split("@");
		for(String stationPoll : stationPolls){
			String[] stationPollInfo = stationPoll.split(":");
			if(stationPollInfo.length < 2){
				continue;
			}
			pollList = stationPollInfo[1].split(",");
		}
		
		Date startDate = sf.parse(startDateStr+" 00:00:00");
		Date endDate = sf.parse(endDateStr + " 23:59:59");
		
		JSONObject resultJsonObject = waterQualityAnalysisService.queryFlux1(startDate, endDate, cycleType, stationIds, stationSNid, pollList);
		outString(resultJsonObject.toString());
	}
	
	
	/**
	 * 污染源削减量分析
	 * gislin
	 * 2016年8月16日
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/queryPollReduct")
	public void queryPollReduction(HttpServletRequest resq, HttpServletResponse res) throws ParseException{
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String cycleType = RequestUnit.getString("cycleType");
		String stationid = RequestUnit.getString("GXStationid");
		String SNstationId = RequestUnit.getString("contributeCode");
		String reductMethod = RequestUnit.getString("reductMethod");
		String excuteStandard = RequestUnit.getString("excuteStandard");
		String startDateStr = RequestUnit.getString("startDate");
		
		String endDateStr = RequestUnit.getString("endDate");
		String[] GXStationids = stationid.split(",");
		
		String pollCode = RequestUnit.getString("pollCode");
		String[] pollList = null;
		String[] stationPolls = pollCode.split("@");
		for(String stationPoll : stationPolls){
			String[] stationPollInfo = stationPoll.split(":");
			if(stationPollInfo.length < 2){
				continue;
			}
			pollList = stationPollInfo[1].split(",");
		}
		
		Date startDate = sf.parse(startDateStr+" 00:00:00");
		Date endDate = sf.parse(endDateStr + " 23:59:59");
		
		JSONObject resultJsonObject = waterQualityAnalysisService.queryReductData(startDate, endDate, cycleType, GXStationids, SNstationId, pollList,reductMethod,excuteStandard);
		outString(resultJsonObject.toString());
	}
	
	/*
	 * 熊伟
	 * 2016-08-18
	 * 水质分析之   水质数据类别分析
	 */
	@RequestMapping(value="/queryWaterType")
	public void queryWaterType(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		
		try {
			String stationid = RequestUnit.getString("stationid");
			String pollCode = RequestUnit.getString("pollCode");
			String startDateStr = RequestUnit.getString("startDate");
			String endDateStr = RequestUnit.getString("endDate");
			String riverCode = RequestUnit.getString("riverCode");
			String cycleTypeStr = RequestUnit.getString("cycleType");
			int dateLength = RequestUnit.getInt("dateLength");
			String[] stationIds = stationid.split(",");
			String[] mns = new String[stationIds.length];
			String[] poll = pollCode.split(",");
			String[] riverStr={};
			HashMap<String,List<String>> mulitPolls = getMulitStationPoll();
			boolean isY2Y = false;
			for(int i=0;i<stationIds.length;i++){
				if(stationIds[i].equals("")){
					continue;
				}
				mns[i] = RedisHelper.getInstance().getMNByStationCode(stationIds[i]);
			}
			String pollutants="";
			for(int j=0; j < poll.length;j++) {
				pollutants+="'"+poll[j]+"',";
			}
			pollutants=pollutants.substring(0, pollutants.length()-1);
			if(riverCode !=null) {
				riverStr = riverCode.split(",");
			}
			String river="";
			for(int j=0; j < riverStr.length;j++) {
				river+="'"+riverStr[j]+"',";
			}
			river=river.substring(0, river.length()-1);
			if("Y2Y".equals(RequestUnit.getString("m2my2yType"))){
				isY2Y = true;
			}
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Date start = sf.parse(startDateStr);
			HashMap<String, Object>  waterTyperesult =waterQualityAnalysisService.getWaterType(start,startDateStr, endDateStr, dateLength,isY2Y,cycleTypeStr, mns,stationIds, pollutants,poll,river,mulitPolls);
			HashMap<String, Object> pollIndexResult = waterQualityAnalysisService.queryWaterTypePollIndexM2MY2YReport(start, dateLength, cycleTypeStr, isY2Y, stationIds, poll);
			List <Object> result = new ArrayList<Object>();
			result.add(waterTyperesult);
			result.add(pollIndexResult);
			if(waterTyperesult != null){
				JSONObject resultJson = DataUtil.objectToJsonObject(result);
				outString(resultJson.toString());
			} else {
				outString("");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 污染同比环比分析
	 * gislin
	 * 2016年8月16日
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/queryM2MY2Y")
	public void queryM2MY2Y(HttpServletRequest resq, HttpServletResponse res) throws ParseException{
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		
		String cycleTypeStr = RequestUnit.getString("cycleType");
		String stationid = RequestUnit.getString("stationid");
		String startDateStr = RequestUnit.getString("startDate");
		int dateLength = RequestUnit.getInt("dateLength");
		boolean isY2Y = false;
		String[] stationCodes = stationid.split(",");
		Date startDate = sf.parse(startDateStr);
		HashMap<String,List<String>> mulitPolls = getMulitStationPoll();
		
		if("Y2Y".equals(RequestUnit.getString("m2my2yType"))){
			isY2Y = true;
		}
		
		JSONObject result = waterQualityAnalysisService.queryM2MY2YReport(startDate, dateLength, cycleTypeStr, isY2Y, stationCodes, mulitPolls);
		outString(result.toString());
	}
	
	private HashMap<String, List<String>> getMulitStationPoll(){
		String pollCode = RequestUnit.getString("pollCode");
		HashMap<String,List<String>> mulitPolls = new HashMap<>();
		String[] stationPolls = pollCode.split("@");
		for(String stationPoll : stationPolls){
			String[] stationPollInfo = stationPoll.split(":");
			if(stationPollInfo.length < 2){
				continue;
			}
			String stationCode = stationPollInfo[0];
			String[] polls = stationPollInfo[1].split(",");
			mulitPolls.put(stationCode, Arrays.asList(polls));
		}
		return mulitPolls;
	}
	/**
	 * 
	 * @param BasinAndRiverCountList,流域和河流的站点数目
	 * @param stationInfoList，站点信息
	 * @param excelData 污染物数据
	 * @param header 标题栏污染物名称
	 * @param pollCodes 标题栏污染物code
	 * @param title,sheet名称
	 * @param downloadfilename文件名称
	 * @throws ParserException
	 * @throws IOException
	 */
	
	@SuppressWarnings("deprecation")
	private void responseData(List<RowBase>BasinAndRiverCountList,List<RowBase>stationInfoList,List<HashMap<String, Object>> excelData,List<String> header,List<String> pollCodes,String downloadfilename) throws ParserException, IOException{
		String sheetName =downloadfilename.substring(0, downloadfilename.length()-4);	
		HttpServletResponse res = WebContext.getResponse();
			HttpServletRequest req = WebContext.getRequest();
			res.setContentType("application/x-msdownload;charset=utf-8");
            String agent = req.getHeader("USER-AGENT");  
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent  
                    && -1 != agent.indexOf("Trident")) {// 解决ie下文件名称乱码问题  
  
                String name = java.net.URLEncoder.encode(downloadfilename, "UTF8");  
  
                downloadfilename = name;  
            } else { // 火狐,chrome等
            	downloadfilename = new String(downloadfilename.getBytes("utf-8"), "ISO-8859-1");
            }
			res.setHeader("Content-Disposition","attachment;filename=" + downloadfilename);
			HSSFWorkbook wb = new HSSFWorkbook(); 
			OutputStream out = res.getOutputStream();
			if(excelData!=null && excelData.size()>0) {
				List<RowBase> pollMaxList = waterQualityAnalysisService.queryPollVITypeMaxMun(pollCodes);
				for(int ii=0;ii<excelData.size();ii++) {
					//获取某一年的数据
					HashMap<String, Object> data = excelData.get(ii); 
					Object yearText = data.get("yearText");
					//某一年的sheet名称
					HSSFSheet sheet = wb.createSheet(yearText+"年"+sheetName);
					ExportExcelUtils extUtils = new ExportExcelUtils(wb, sheet);
					//列宽设为自动宽度
			        sheet.setDefaultColumnWidth(10); 
			        // 生成一个样式  
			        HSSFCellStyle style = wb.createCellStyle();  
			        style=extUtils.createCellStyle(wb);
			        HSSFCellStyle cellCenterStyle=wb.createCellStyle();
			        cellCenterStyle=extUtils.cellCenterStyle(wb);
			        // 生成一个字体  
			        HSSFFont font = wb.createFont();  
			        font.setColor(HSSFColor.BLACK.index);  
			        font.setFontHeightInPoints((short) 12);  
			        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
			        // 把字体应用到当前的样式  
			        style.setFont(font);  
					@SuppressWarnings("unchecked")
					List<RowBase> datas = (List<RowBase>)data.get("datas");
					//设置标题
					extUtils.createNormalHead(yearText+"年深圳市河流水质监测结果统计",2+pollCodes.size());
					//设置表头（流域、河流、站点以及污染物名称）
					HSSFRow row=sheet.createRow(1);
					row.setHeight((short)(15*20));
					//填充表头数据
			        for (int j = 0; j < header.size(); j++) {  
			            HSSFCell cell = row.createCell((short) j);  
			            cell.setCellStyle(style);  
			            HSSFRichTextString text = new HSSFRichTextString(header.get(j));  
			            cell.setCellValue(text.toString());  
			        }  
			        //过滤掉最大值和最小值数据，此统计表格中只显示均值数据
			        List<RowBase>avgData = new ArrayList<>();
			        for(RowBase rows:datas) {
			        	String valueType = rows.getSafeString("VALUE_TYPE");
			        	if("AVG".equals(valueType)) {
			        		avgData.add(rows);
			        	}
			        }
			        // 遍历集合数据，产生数据行  
			        if (datas != null) {  
			        	//数据部分从index=2行开始填充	              
						int riverBasinRows=0;
						int riverStationNum=0;
	                    //标识目前站点处于第几行（row从0开始）
                    	int  flag=0;
                    	//isFirst用于标识是否新增了第一行流域和站点行，如果已经新增了则
                    	boolean isFirst=true;
						int BASINTOTAL_COUNT=0;
						int number=0;
						HSSFRow row2 = sheet.createRow(2);
						for(int m=0;m<BasinAndRiverCountList.size();m++) {
							//如果是第一条流域，创建第index=2的数据行，如果不是第一个则在第一个流域的行数基础上+2.
							if(isFirst) {
								row2 = sheet.createRow(2);
							} else {
								row2 = sheet.createRow(2+riverBasinRows);
								number=2+riverBasinRows;
							}
							HSSFCell cell0 = row2.createCell((short) 0); 
							RowBase riverRow = BasinAndRiverCountList.get(m);
							String basinRiverName = riverRow.getSafeString("RIVER_BASIN_NAME");
							String riverCode = riverRow.getSafeString("RIVER_CODE");
							BASINTOTAL_COUNT = riverRow.getSafeInt("BASINTOTAL_COUNT");
							String riverName = riverRow.getSafeString("RIVER_NAME");
							int stationCount = riverRow.getSafeInt("STATION_COUNT");
							riverBasinRows+=BASINTOTAL_COUNT;
							riverStationNum+=stationCount;
							
		                    //合并单元格
		                    if(m==0) {
			                    //1、流域合并单元格
						        sheet.addMergedRegion(new Region(2,(short)0,1+BASINTOTAL_COUNT,(short)0));
						      //1、河流合并单元格
						        sheet.addMergedRegion(new Region(2,(short)1,1+stationCount,(short)1)); 
		                    } else {
			                    //流域合并单元格
						        sheet.addMergedRegion(new Region(2+riverBasinRows-BASINTOTAL_COUNT,(short)0,riverBasinRows+1,(short)0));
						      //河流合并单元格
						        sheet.addMergedRegion(new Region(2+riverStationNum-stationCount,(short)1,riverStationNum+1,(short)1)); 
		                    }
				             //2、填充流域数据
		                    cell0.setCellStyle(cellCenterStyle);
		                    cell0.setCellValue(basinRiverName); 
					        //2、填充河流数据
							HSSFCell cell1 = row2.createCell((short) 1);   
							cell1.setCellStyle(cellCenterStyle);
		                    cell1.setCellValue(riverName);
		                    for(int n=0;n<stationInfoList.size();n++) {
		                    	RowBase stationInfo = stationInfoList.get(n);
		                    	String riverS = stationInfo.getSafeString("RIVER_CODE");
		                    	String stationNameS = stationInfo.getSafeString("NAME");
		                    	String stationCodeS = stationInfo.getSafeString("CODE");
		                    	if(riverCode.equals(riverS)) {
						        	if(isFirst){
						        		isFirst=false;
						        	} else {
						        		flag++;
						        		int rowIndex = 2+flag;
						        		//如果已经该行号的row已经创建了，不用重复创建覆盖数据
						        		if(rowIndex!=number) {
						        			row2 = sheet.createRow(rowIndex);
						        		}
						        	}
					        		//3、创建断面名称cell
							        HSSFCell cell2 = row2.createCell((short) 2); 
							        //3、填充断面名称cell
							        cell2.setCellStyle(cellCenterStyle);
							        cell2.setCellValue(stationNameS);
					            	int cellIndex = 3;
					            	//遍历所选择的所有参数
					            	for(int mm=0;mm<pollCodes.size();mm++) {
					            		String pollCode = pollCodes.get(mm);
					            		//isExsits，用于标识该站点是否有该污染物，由于表头显示的污染物是选择的污染物的并集，因此，在寻找某个站点的污染物的时候可能
					            		//查找不到，因此要标识是否有该污染物，如果没有则用“-”代替值。
					            		boolean isExsits = false;
							            for (RowBase rows : avgData) {
							            	String codes = rows.getSafeString("STATION_CODE");  
							            	String parmCodes = rows.getSafeString("PARMNAME");
							            	//年份、站点、污染物都要对应上取值，和表头对应上，否则数据和表头污染物不对应。
							            	if(stationCodeS.equals(codes)&&parmCodes.equals(pollCode)) {
							            		isExsits=true;
								                String avrValue = rows.getSafeString("P"+yearText+"年"); 
								                double value=0;
								                //4、创建污染物参数cells
							                    HSSFCell cells = row2.createCell((short) cellIndex); 
								                if(!"".equals(avrValue)) {
								                	value = Double.parseDouble(avrValue);
									                BigDecimal   b   =   new   BigDecimal(avrValue);  
									                value =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue(); 
									                cells.setCellStyle(cellCenterStyle);
									                cells.setCellValue(value);
								                }else {
								                	cells.setCellStyle(cellCenterStyle);
							                    	cells.setCellValue("--");  	
							                    }
							                    cellIndex++; 
							                    break;
							            	}
							            }
							            if(!isExsits) {
							            	HSSFCell cells = row2.createCell((short) cellIndex); 
							            	cells.setCellStyle(cellCenterStyle);
							            	cells.setCellValue("--");
							            	cellIndex++; 
							            }
					              }
		                    	}
		                    }
						}
						int maxRowNum = riverBasinRows;
						HSSFRow roww = sheet.createRow(2+maxRowNum);
						HSSFCell cells = roww.createCell((short)0);
						sheet.addMergedRegion(new Region(2+maxRowNum,(short)0,2+maxRowNum,(short)1));
						cells.setCellValue("地表水V类标准(≤)");
						int cellIndex=3;
						for(int dd=0;dd<pollCodes.size();dd++) {
							boolean dataFlag=false;
							String poCode = pollCodes.get(dd);
							for(int kk=0;kk<pollMaxList.size();kk++) {
								RowBase maxValueRow = pollMaxList.get(kk);
								String item = maxValueRow.getSafeString("ITEM");
								double maxValue = maxValueRow.getSafeDouble("MAXMUM");
								if(poCode.equals(item)) {
									dataFlag = true;
									HSSFCell cellSS = roww.createCell(cellIndex);
									cellSS.setCellStyle(cellCenterStyle);
									cellSS.setCellValue(maxValue);
									cellIndex++;
								}
							}
							if(!dataFlag) {
								HSSFCell cellSS = roww.createCell(cellIndex);
								cellSS.setCellStyle(cellCenterStyle);
								cellSS.setCellValue("--");
								cellIndex++;
							}
						}
			         }  
			        extUtils.setWb(wb);
			        extUtils.setSheet(sheet);
			        }
					wb.write(out);
					out.flush();
					out.close();
				}
			}
	
}
